import warnings
from typing import Dict, List


def get_records_revised(self, env: Dict) -> List:
    """Get all registered records that are valid in the given environment
    from record table.

    If the backend and IR of rewriter are set to 'default', then the
    rewriter is regarded as default rewriter. The default rewriter will be
    activated only when all other rewriters are not valid. If there are
    multiple rewriters are valid (except default rewriter), we will
    activate the first one (The order is determined by the time when
    rewriters are loaded).

    Args:
        env (dict): Environment dictionary that includes backend, IR,
            codebase version, etc.

    Returns:
        List: A list that includes valid records.
    """
    default_records = list()
    records = list()

    for origin_function, rewriter_records in self._rewrite_records.items():
        default_rewriter = None
        final_rewriter = None
        cnt_valid = 0

        for record in rewriter_records:
            # Get the checkers of current rewriter
            checkers: List[Checker] = record['_checkers']

            # Check if the rewriter is default rewriter
            if len(checkers) == 0:
                default_rewriter = record
                cnt_valid += 1
            else:
                # Check if the checker is valid.
                # The checker is valid only if all the checks are passed
                valid = True
                for checker in checkers:
                    if not checker.check(env):
                        valid = False
                        break
                if valid:
                    final_rewriter = record
                    cnt_valid += 1

        # Check if there are multiple valid rewriters
        if cnt_valid > 1:
            warnings.warn(
                f'\nDetect {cnt_valid} valid rewriters for '
                f'{origin_function}, use the last valid rewriter.')

        # Append final rewriter.
        # If there is no valid rewriter, try not apply default rewriter
        if final_rewriter is not None:
            records.append((origin_function, final_rewriter))
        elif default_rewriter is not None:
            default_records.append((origin_function, default_rewriter))

    # Make the default records como to the front of list because we may
    # want the non-default records to override them.
    return default_records + records
